﻿using System;
using System.IO;
using System.Windows;
using System.Windows.Media.Imaging;

namespace Auktionshuset
{
    public partial class AuctionWindow
    {
        public Auction Auction { get; set; }

        private readonly Connection _conn;

        public AuctionWindow(Connection conn, Auction auction)
        {
            Auction = auction;
            _conn = conn;

            InitializeComponent();

            ProductNameTextBlock.Text = Auction.Title;
            DescriptionTextBlock.Text = Auction.Description;

            if (Auction.ImageBytes.Length > 0)
            {
                BitmapImage image = new BitmapImage();
                MemoryStream stream = new MemoryStream(Auction.ImageBytes);
                stream.Seek(0, SeekOrigin.Begin);
                image.BeginInit();
                image.StreamSource = stream;
                image.EndInit();
                ProductImage.Source = image;
            }

            Refresh(true);
        }

        public new void Show()
        {
            base.Show();
            _conn.RequestAuctionUpdate(Auction);
        }

        public void Refresh()
        {
            Refresh(false);
        }

        public void Refresh(bool forceRefresh)
        {
            Dispatcher.BeginInvoke(new Action(() =>
            {
                if (forceRefresh || Auction.StatusMessage == "")
                {
                    CurrentTextBlock.Text = "Aktuelt bud: " + Auction.CurrentBid + " kr";
                    PlaceBidButton.Content = "Byd " + Auction.NextBid + " kr";
                    if (!Auction.Active)
                    {
                        CurrentTextBlock.Text = "Auktionen er lukket: " + Auction.CurrentBid + " kr";
                        PlaceBidButton.IsEnabled = false;
                    }

                    if (Auction.HighestBidder != null)
                    {
                        BroadcastFeedTextBlock.Text = Auction.HighestBidder.Alias + " har budt: " + Auction.CurrentBid + " kr.\r\n" + BroadcastFeedTextBlock.Text;
                    
                        PlaceBidButton.IsEnabled = Auction.HighestBidder.Username != _conn.User.Username;
                    }
                }

                if (Auction.StatusMessage != null)
                {
                    HammerTextBlock.Text = Auction.StatusMessage;
                }
            }));
        }

        private void PlaceBidButton_Click(object sender, RoutedEventArgs e)
        {
            _conn.SendPlaceBid(Auction.Id, Auction.NextBid);
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            _conn.UnsubscribeToAuction(this);
        }
    }
}
